const { Comment, User, Note, Video } = require('../models');
const { generateUniqueId } = require('../utils/authUtils');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 创建评论
const createComment = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { content, note_id, video_id } = req.body;
    const userId = req.user.id;

    // 验证必须提供note_id或video_id中的一个
    if (!note_id && !video_id) {
      return res.status(400).json({ message: '必须指定评论的笔记或视频' });
    }

    // 检查关联的笔记或视频是否存在
    if (note_id) {
      const note = await Note.findByPk(note_id);
      if (!note) {
        return res.status(404).json({ message: '评论的笔记不存在' });
      }
    }

    if (video_id) {
      const video = await Video.findByPk(video_id);
      if (!video) {
        return res.status(404).json({ message: '评论的视频不存在' });
      }
    }

    // 创建评论
    const comment = await Comment.create({
      id: generateUniqueId(),
      content,
      user_id: userId,
      note_id,
      video_id,
      created_at: new Date()
    });

    // 更新关联的笔记或视频的评论数
    if (note_id) {
      await Note.findByPk(note_id).then(note => {
        if (note) note.increment('comments');
      });
    }

    if (video_id) {
      await Video.findByPk(video_id).then(video => {
        if (video) video.increment('comments');
      });
    }

    // 返回带用户信息的评论
    const createdComment = await Comment.findByPk(comment.id, {
      include: [{ model: User, attributes: ['id', 'username', 'avatar'] }]
    });

    res.status(201).json({
      message: '评论成功',
      comment: {
        id: createdComment.id,
        content: createdComment.content,
        user: {
          id: createdComment.User.id,
          username: createdComment.User.username,
          avatar: createdComment.User.avatar
        },
        created_at: createdComment.created_at
      }
    });
  } catch (error) {
    console.error('创建评论失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取笔记或视频的评论列表
const getComments = async (req, res) => {
  try {
    const { note_id, video_id, page = 1, limit = 20 } = req.query;
    
    if (!note_id && !video_id) {
      return res.status(400).json({ message: '必须指定笔记ID或视频ID' });
    }

    const where = {};
    if (note_id) where.note_id = note_id;
    if (video_id) where.video_id = video_id;

    const offset = (page - 1) * limit;

    const { count, rows: comments } = await Comment.findAndCountAll({
      where,
      include: [{ model: User, attributes: ['id', 'username', 'avatar'] }],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    const formattedComments = comments.map(comment => ({
      id: comment.id,
      content: comment.content,
      user: {
        id: comment.User.id,
        username: comment.User.username,
        avatar: comment.User.avatar
      },
      created_at: comment.created_at
    }));

    res.status(200).json({
      comments: formattedComments,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取评论列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除评论
const deleteComment = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 查找评论
    const comment = await Comment.findByPk(id);
    if (!comment) {
      return res.status(404).json({ message: '评论不存在' });
    }

    // 检查权限（只有评论作者可以删除）
    if (comment.user_id !== userId) {
      return res.status(403).json({ message: '没有权限删除此评论' });
    }

    // 保存关联信息用于后续更新评论数
    const { note_id, video_id } = comment;

    // 删除评论
    await comment.destroy();

    // 更新关联的笔记或视频的评论数
    if (note_id) {
      await Note.findByPk(note_id).then(note => {
        if (note && note.comments > 0) note.decrement('comments');
      });
    }

    if (video_id) {
      await Video.findByPk(video_id).then(video => {
        if (video && video.comments > 0) video.decrement('comments');
      });
    }

    res.status(200).json({ message: '评论删除成功' });
  } catch (error) {
    console.error('删除评论失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员删除评论
const adminDeleteComment = async (req, res) => {
  try {
    const { id } = req.params;

    // 查找评论
    const comment = await Comment.findByPk(id);
    if (!comment) {
      return res.status(404).json({ message: '评论不存在' });
    }

    // 保存关联信息用于后续更新评论数
    const { note_id, video_id } = comment;

    // 管理员可以直接删除
    await comment.destroy();

    // 更新关联的笔记或视频的评论数
    if (note_id) {
      await Note.findByPk(note_id).then(note => {
        if (note && note.comments > 0) note.decrement('comments');
      });
    }

    if (video_id) {
      await Video.findByPk(video_id).then(video => {
        if (video && video.comments > 0) video.decrement('comments');
      });
    }

    res.status(200).json({ message: '评论删除成功' });
  } catch (error) {
    console.error('删除评论失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户的评论历史
const getUserComments = async (req, res) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 20 } = req.query;
    
    const offset = (page - 1) * limit;

    const { count, rows: comments } = await Comment.findAndCountAll({
      where: { user_id: userId },
      include: [
        { model: User, attributes: ['id', 'username', 'avatar'] },
        { model: Note, attributes: ['id', 'title'] },
        { model: Video, attributes: ['id', 'title'] }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    const formattedComments = comments.map(comment => ({
      id: comment.id,
      content: comment.content,
      user: {
        id: comment.User.id,
        username: comment.User.username,
        avatar: comment.User.avatar
      },
      target: comment.note_id ? 
        { type: 'note', id: comment.Note.id, title: comment.Note.title } :
        { type: 'video', id: comment.Video.id, title: comment.Video.title },
      created_at: comment.created_at
    }));

    res.status(200).json({
      comments: formattedComments,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取用户评论历史失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createComment,
  getComments,
  deleteComment,
  adminDeleteComment,
  getUserComments
};